package com.study.qqserve.service;

import com.study.qqcommon.Message;
import com.study.qqcommon.MessageType;

import java.io.*;
import java.net.Socket;
import java.util.HashMap;

public class ServerContentThread extends Thread {
    private Socket socket;
    private String userId;
    private ObjectOutputStream oos;
    private ObjectInputStream ois;

    public ServerContentThread(Socket socket, String userId) throws IOException {
        this.socket = socket;
        this.userId = userId;
        this.oos = new ObjectOutputStream(socket.getOutputStream());
        this.ois = new ObjectInputStream(socket.getInputStream());
    }


    public ObjectOutputStream getObjectOutputStream() {
        return oos;
    }

    @Override
    public void run() {
        while (true) {
            try {
                System.out.println("服务端和客户端 " + userId + " 保持通讯");

                Message message = (Message) ois.readObject();
                System.out.println("接收到从客户端发来的消息：" + message);
                switch (message.getMesType()) {
                    case MessageType.MESSAGE_GET_ONLINE_FRIEND:
                        System.out.println(message.getSender() + " 请求在线用户列表");
                        oos.writeObject(getMessage(message));
                        System.out.println("服务端发送在线用户列表给客户端 " + getMessage(message));
                        break;
                    case MessageType.MESSAGE_CLIENT_EXIT:
                        MangerClientThreads.removeServerContentThread(message.getSender());
                        socket.close();
                        System.out.println(message.getSender() + " 退出");
                        return;
                    case MessageType.MESSAGE_COMM_MES:
                        System.out.println(message.getSender() + " 给 " + message.getGetter() + " 发送消息：" + message.getContent());

                        if (!MangerClientThreads.isOnline(message.getGetter())) {
                            System.out.println("用户不在线，保存到数据库，将消息存储在离线缓存中");
                            OfflineMessagesService.addOfflineMessage(message.getGetter(), message);
                        } else {
                            ServerContentThread serverContentThread = MangerClientThreads.getServerContentThread(message.getGetter());
                            serverContentThread.getObjectOutputStream().writeObject(message);
                        }
                        break;
                    case MessageType.MESSAGE_TO_ALL_MES:
                        HashMap<String, ServerContentThread> hm = MangerClientThreads.getAllServerContentThread();
                        for (String onlineUserId : hm.keySet()) {
                            if (!onlineUserId.equals(message.getSender())) {
                                ServerContentThread serverContentThread_ALL_MES = MangerClientThreads.getServerContentThread(onlineUserId);
                                serverContentThread_ALL_MES.getObjectOutputStream().writeObject(message);
                            }
                        }
                        break;
                    case MessageType.MESSAGE_FILE_MES:
                        if (!MangerClientThreads.isOnline(message.getGetter())) {
                            System.out.println("用户不在线，保存到数据库，将消息存储在离线缓存中");
                            OfflineMessagesService.addOfflineMessage(message.getGetter(), message);
                        } else {
                            System.out.println("服务端收到客户端发来的文件消息");
                            ServerContentThread serverContentThread_file = MangerClientThreads.getServerContentThread(message.getGetter());
                            serverContentThread_file.getObjectOutputStream().writeObject(message);
                        }
                        break;
                    default:
                        System.out.println("服务端收到客户端发来的其他消息类型：" + message.getMesType());
                        break;
                }
            }  catch (StreamCorruptedException e) {
                System.err.println("数据流损坏，可能是由于客户端异常断开连接：" + e.getMessage());
                // 尝试重新建立连接或清理资源
                break;
            } catch (IOException | ClassNotFoundException e) {
                System.err.println("发生异常：" + e.getMessage());
                e.printStackTrace();
                break;
            }
        }
    }

    private Message getMessage(Message message) throws IOException {
        String userOnlineIds = MangerClientThreads.getOnlineUser();
        System.out.println("在线用户列表：" + userOnlineIds);
        Message msg = new Message();
        msg.setMesType(MessageType.MESSAGE_RET_ONLINE_FRIEND);
        msg.setContent(userOnlineIds);
        msg.setGetter(message.getSender());
        return msg;
    }
}